﻿using SAIM.Models;
using SAIM.Models.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SAIM.Controllers
{
    [Authorize]
    public class ApplicationsController : Controller
    {
        /*
        private SAIMIdentity UserIdentity
        {
            get { return new SAIMIdentity(User.Identity); }
        }
        public enum ApplicationMessage
        {
            ApplicationCreatedSuccessfully,
            ApplicationRemoveSuccesfully
        }

        //GET: Applications/Index
        public ActionResult Index()
        {
            using (ApplicationsBLL applications = new ApplicationsBLL())
            {
                return View( new IndexApplicationViewModel(applications.getUserApplications(UserIdentity.GetUserId())) );
            }
        }

        // GET: Applications/Immovables
        public ActionResult Immovables(ApplicationMessage? message)
        {
            ViewBag.StatusMessage = GetStatusMessage(message);
            return View(new ImmovablesViewModel() { ReservationDate = DateTime.Now });
        }

        //
        // POST: Applications/Immovables
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Immovables(ImmovablesViewModel model)
        {
            // Validación del modelo
            if (ModelState.IsValid)
            {
                // Verificación de validez de fecha seleccionada
                if(model.ReservationDate.CompareTo(DateTime.Now.AddDays(-1)) < 0 )
                    ModelState.AddModelError("", "El día y la hora seleccionados no son válidos");
                else
                    using (ApplicationsBLL applications = new ApplicationsBLL())
                    {
                        // Verificación de disponibilidad de horario
                        if (applications.getApplication(UserIdentity.GetUserId(), model.Immovable, model.ReservationDate) == null)
                        {
                            // Creación de la solicitud
                            bool succes = applications.insertApplication(
                                UserIdentity.GetUserId(), 
                                model.Immovable, 
                                model.ReservationDate, 
                                model.Observations);
                            if (!succes)
                                ModelState.AddModelError("", "Imposible reservar inmueble, intente más tarde.");
                            else
                            {
                                // Solicitud creada exitosamente
                                return RedirectToAction("Immovables", new { message = ApplicationMessage.ApplicationCreatedSuccessfully });
                            }
                        }
                        else 
                        {
                            ModelState.AddModelError("", "El día y la hora seleccionados no se encuentran disponibles");
                        }
                    }
                return View(model);
            }

            return View(model);
        }

        // GET: Applications/Summary
        public ActionResult Summary(string id)
        {
            if (id == null)
                return RedirectToAction("Index");
            else 
            {
                using (AspNetUsersBLL user = new AspNetUsersBLL(UserIdentity.GetUserId()))
                {
                    if (user.isInRole("Manage applications")) // Usuario administrativo
                    {
                        using (ApplicationsBLL applications = new ApplicationsBLL())
                        {
                            try
                            {
                                return View( new SummaryApplicationViewModel( applications.getApplication(long.Parse(id)) ) );
                            }
                            catch (Exception)
                            {
                                return RedirectToAction("Index");
                            }
                        }
                    }
                    else // Usuario común
                    {
                        using (ApplicationsBLL applications = new ApplicationsBLL())
                        {
                            try
                            {
                                return View(new SummaryApplicationViewModel(applications.getApplication(long.Parse(id), UserIdentity.GetUserId())));
                            }
                            catch (Exception)
                            {
                                return RedirectToAction("Index");
                            }
                        }
                    }
                }
            }
        }*/

        // GET: Applications/File
        /*public ActionResult File(string id)
        {
            if (id == null)
                return RedirectToAction("Index");
            else
            {
                using (AspNetUsersBLL user = new AspNetUsersBLL(UserIdentity.GetUserId()))
                {
                    if (user.isInRole("Manage applications")) // Usuario administrativo
                    {
                        using (ApplicationsBLL applications = new ApplicationsBLL())
                        {
                            try
                            {
                                return new RazorPDF.PdfResult(new SummaryApplicationViewModel( applications.getApplication(long.Parse(id)) ), "File" );
                            }
                            catch (Exception)
                            {
                                return RedirectToAction("Index");
                            }
                        }
                    }
                    else // Usuario común
                    {
                        using (ApplicationsBLL applications = new ApplicationsBLL())
                        {
                            try
                            {
                                return new RazorPDF.PdfResult(new SummaryApplicationViewModel(applications.getApplication(long.Parse(id), UserIdentity.GetUserId())), "File");
                            }
                            catch (Exception)
                            {
                                return RedirectToAction("Index");
                            }
                        }
                    }
                }
            }
        }*/

        /*
        //
        // POST: Applications/Cancel
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Cancel(SummaryApplicationViewModel model)
        {
            // Validación del modelo
            if (ModelState.IsValid)
            {
                // Validación: La solicitudes solo se cancelan con un día o más de anticipación
                if (model.reservationDate.CompareTo(DateTime.Now.AddDays(1)) < 0)
                    ModelState.AddModelError("", "Solo se pueden cancelar solicitudes con un día(24h) o más de anticipación.");
                using (ApplicationsBLL applications = new ApplicationsBLL())
                {
                    // Cancelación (Eliminación de la solicitud de inmuebles)
                    bool succes = applications.deleteApplication(model.Id);
                    if(succes)
                        return RedirectToAction("Immovables", new { message = ApplicationMessage.ApplicationRemoveSuccesfully });
                }
            }
            ModelState.AddModelError("", "No se pudo cancelar la solicitud. Por favor intente más tarde.");
            using (ApplicationsBLL applications = new ApplicationsBLL())
            {
                try
                {
                    return View( "Summary", UserIdentity.GetUserId() );
                }
                catch (Exception)
                {
                    return RedirectToAction("Index");
                }
            }
        }

        //GET: Applications/Manage
        public ActionResult Manage()
        {
            using (AspNetUsersBLL user = new AspNetUsersBLL(UserIdentity.GetUserId()))
            {
                if (user.isInRole("Manage applications"))
                {
                    using (ApplicationsBLL applications = new ApplicationsBLL())
                    {
                        return View(new ManageApplicationsViewModel(applications.getAllApplications()));
                    }
                }
                else
                {
                    throw new HttpException(403, "Access Denied");
                }
            }
        }

        private string GetStatusMessage(ApplicationMessage? message)
        {
            string statusMessage =
            message == ApplicationMessage.ApplicationCreatedSuccessfully ? "Inmueble reservado exitosamente" :
            message == ApplicationMessage.ApplicationRemoveSuccesfully ? "Solicitud cancelada exitosamente" : "";

            return statusMessage;
        }
        */
    }
}